package name.fowler.refactoring.simplestore.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import name.fowler.refactoring.simplestore.domain.Rental;

public class RentalRepository {
	@PersistenceUnit
	private EntityManagerFactory entityManagerFactory;
	
	public RentalRepository() {};
	
	// This constructor is for testing only
	public RentalRepository(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}
	
	public void addRental(Rental r) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.persist(r);
        entityManager.getTransaction().commit();
	}
	
	public void removeRental(Rental r) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.remove(r);
        entityManager.getTransaction().commit();
	}
	
	public void updateRental(Rental r) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.merge(r);
        entityManager.getTransaction().commit();
	}
	
	public List<Rental> queryAll() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<Rental> Rentals = entityManager
				.createNamedQuery("Rental.findAll", Rental.class)
				.getResultList();
		entityManager.close();
		return Rentals;
	}
}
